package com.renren.project.db.validator.phone;

import com.renren.project.db.validator.ValidationUtils;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 中国手机号格式校验
 */
public class PhoneValidationImpl implements ConstraintValidator<PhoneValidation,String> {

    private boolean required = false;

    @Override
    public void initialize(PhoneValidation phoneValidation) {
        required = phoneValidation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if(required){
            return ValidationUtils.isPhone(value);
        }else{
            if(StringUtils.isBlank(value)){
                return true;
            }else{
                return ValidationUtils.isPhone(value);
            }
        }
    }

    private boolean isPhone(String str,String regulation) {
        Pattern pattern = Pattern.compile(regulation);
        return pattern.matcher(str).matches();
    }

}
